import os
import sys
from pathlib import Path
from flask import request, jsonify, send_from_directory
from werkzeug.utils import secure_filename

# 导入TestMyDeepSeekDemo模块
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from TestMyDeepSeekDemo1 import process_test_case_generation

def register_routes(app):
    """
    注册所有路由到Flask应用
    """
    
    @app.route('/')
    def index():
        """
        提供前端页面
        """
     
        
        #方法2: 如果您想使用Client目录下的静态文件，可以使用下面的代码替代上面的代码
        return send_from_directory('../Client', 'Index.html')

    @app.route('/generate-test-cases', methods=['POST'])
    def handle_generate_test_cases():
        try:
            if 'file' not in request.files:
                return jsonify({'error': 'No file uploaded'}), 400

            file = request.files['file']
            if file.filename == '':
                return jsonify({'error': 'No file selected'}), 400

            # 创建上传文件夹（如果不存在）
            upload_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
            if not os.path.exists(upload_folder):
                os.makedirs(upload_folder)
            
            # 保存上传的文件
            filename = secure_filename(file.filename)
            file_path = os.path.join(upload_folder, filename)
            file.save(file_path)
            
            # 设置CSV输出路径
            csv_filename = f"test_cases_{os.path.splitext(filename)[0]}.csv"
            csv_path = os.path.join(upload_folder, csv_filename)
            
            # 调用测试用例生成函数
            success, result = process_test_case_generation(file_path, csv_path)
            
            if success:
                # 读取生成的CSV文件
                with open(csv_path, 'r', encoding='utf-8') as f:
                    csv_content = f.read()
                
                # 返回CSV内容
                if isinstance(result, list):
                    return jsonify({'test_cases': result}), 200
                return jsonify({'error': 'Invalid data format'}), 500
            else:
                return jsonify({'error': result, 'code': 500}), 500
        except Exception as e:
            import traceback
            error_details = traceback.format_exc()
            print(f"Error in generate-test-cases: {error_details}")
            return jsonify({'error': str(e)}), 500

    @app.route('/health', methods=['GET'])
    def health_check():
        return jsonify({'status': 'ok'}), 200

    # 静态文件路由
    @app.route('/js/<path:filename>')
    def serve_js(filename):
        return send_from_directory('../Client/js', filename)

    @app.route('/styles/<path:filename>')
    def serve_css(filename):
        return send_from_directory('../Client/styles', filename)

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory('../Client', 'favicon.ico', mimetype='image/vnd.microsoft.icon')